package com.brtbeacon.wx.demo.mapview;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.brtbeacon.wx.map.BRTMapWebViewX5Activity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;

public class MapWebViewActivity extends BRTMapWebViewX5Activity {

    public static void startActivity(Context ctxt, String url) {
        Intent intent = new Intent(ctxt, MapWebViewActivity.class);
        intent.putExtra(PARAM_URL, url);
        ctxt.startActivity(intent);
    }

    private long lastKeyBackTimeMillis = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if(webView.canGoBack()) {
                webView.goBack();
                return true;
            }

            long keyBackTimeMillis = Calendar.getInstance().getTimeInMillis();
            if (keyBackTimeMillis - lastKeyBackTimeMillis >= 1000) {
                Toast.makeText(this, "再按一次返回，退出地图演示!", Toast.LENGTH_SHORT).show();
                lastKeyBackTimeMillis = keyBackTimeMillis;
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onInitWebView() {
        //  添加window.ysApi全局对象供页面端调用
        webView.addJavascriptInterface(ysApi,"ysApi");
    }

    /**
     * 设置用户数据，传入null给userId将设置成undefined;
     * @param userId
     * @param loginTime
     * 为页面全局对象 window.ysApi.userData 设置自定义数据。
     */
    private void setUserData(String userId, long loginTime) {
        String script = null;
        if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(userId.trim())) {
            script = "window.ysApi.userData = undefined;";
        } else {
            //把 ysApi.userData设置成包含 userId, loginTime属性的对象
            JSONObject jsonData = new JSONObject();
            try {
                jsonData.put("userId", userId);
                jsonData.put("loginTime", loginTime);
                //TODO.. 可以添加自定义属性 jsonData.put("新的属性", "属性值");
            } catch (Exception e) {}
            script = "window.ysApi.userData = " + jsonData.toString();
        }
        webView.evaluateJavascript(script, null);
    }

    //  页面全局对象 ysApi 实现
    private Object ysApi = new Object() {
        /**
         * 添加用户登录接口
         */
        @JavascriptInterface
        public void login() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //TODO... 添加你的登录弹出对话框。当用户登录成功后，请调用setUserData()
                    Toast.makeText(MapWebViewActivity.this, "用户登录成功!", Toast.LENGTH_SHORT).show();
                    setUserData("测试登录", Calendar.getInstance().getTimeInMillis());
                }
            });
        }

    };

}

